package com.cfl.elasticsearch.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cfl.elasticsearch.utils.AppResponse;
import com.cfl.elasticsearch.utils.ElasticsearchUtils;

@Controller
@RequestMapping("")
public class HomeController {
	
	@RequestMapping("/")
	public String home() {
		return "home";
	}
	
	/**
	 * 插入数据
	 * @return
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object add() {
		ElasticsearchUtils elasticsearchUtils = ElasticsearchUtils.share();
		ArrayList<String> strArray = new ArrayList<String>();
		strArray.add("陈");
		strArray.add("小");
		strArray.add("正");
		strArray.add("中");
		strArray.add("华");
		strArray.add("人");
		strArray.add("民");
		strArray.add("共");
		strArray.add("和");
		strArray.add("国");
		for(int i = 0; i < 100000; i++)
		{
			String name = strArray.get(getRandom(10)) + strArray.get(getRandom(10)) + strArray.get(getRandom(10));
			String content = strArray.get(getRandom(10));
			int sex = getRandom(100)%2;
			int age = getRandom(100);
			System.out.println("sex: " + sex);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", i);
			map.put("name", name);
			map.put("content", content);
			map.put("age", age);
			map.put("sex", sex);
			elasticsearchUtils.index("account", "user", i+"", map);
		}
		return new AppResponse("");
	}
	public int getRandom(int max)
	{
		Random random = new Random();// 定义随机类
		int result=random.nextInt(max);// 返回[0,10)集合中的整数，注意不包括10
		return result;
	}
	
	// 查询数据
	@RequestMapping(value = "/search")
	@ResponseBody
	public Object search(String name, Integer sex, Integer minAge, Integer maxAge, Integer page, Integer pageSize) {
		System.out.println("name: " + name + " sex: " + sex + " minAge: " + minAge + " maxAge: " + maxAge + " page:" + page + " pageSize:" + pageSize);
		if(minAge == null) minAge = 0;
		if(maxAge == null) maxAge = 100;
		if(page == null || page < 1) page = 1;
		if(pageSize == null || pageSize < 1) pageSize = 20;
		
		ElasticsearchUtils elasticsearchUtils = ElasticsearchUtils.share();
		List<Map<String, Object>> maps = elasticsearchUtils.getByNamePage("account", "user", name, sex, minAge, maxAge, page, pageSize);
		return new AppResponse(maps);
	}
}
